package com.ljf.eslab.lab.interceptor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ljf.eslab.lab.entity.TeacherEntity;
import com.ljf.eslab.lab.service.TeacherService;
import com.ljf.eslab.lab.service.UserTokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    UserTokenService userTokenService;

    @Autowired
    TeacherService teacherService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        System.out.printf("--------------");
        log.debug("拿到了token:{}", token);
        if (!StringUtils.isEmpty(token)) {
            Long idByToken = userTokenService.getIdByToken(token);
            request.setAttribute("userId", idByToken);
            log.debug("拿到了userId:{}", idByToken);
            //teacherId
            //找到userid对应teacherid
            Integer tid = teacherService.getIdByUserId(idByToken);
            log.debug("teacherID:{}", tid);
            if (tid != null) {
                request.setAttribute("tid", tid);
                log.debug("拿到了teacherId:{}", request.getAttribute("tid"));
            }
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
